using System.Windows.Forms;

namespace SpellCenter.UI
{
    public class UIFunctions : IUIFunctions
    {
        public bool DirectoryDialog(out string dir)
        {
            return DirectoryDialog(out dir, null);
        }

        public bool DirectoryDialog(out string dir, IWin32Window owner)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.ShowNewFolderButton = false;
            DialogResult result = ShowDialog(dialog, owner);
            dir = dialog.SelectedPath;
            return ResultIsOk(result);
        }

        private static bool ResultIsOk(DialogResult result)
        {
            return (result & DialogResult.OK) != 0;
        }

        private static DialogResult ShowDialog(CommonDialog dialog, IWin32Window owner)
        {
            DialogResult result;
            if(owner != null)
                result = dialog.ShowDialog(owner);
            else 
                result = dialog.ShowDialog();
            return result;
        }

        public bool OpenFileDialog(out string file)
        {
            return OpenFileDialog(out file, null);
        }

        public bool OpenFileDialog(out string file, IWin32Window owner)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            DialogResult result = ShowDialog(dialog, owner);
            file = dialog.FileName;
            if(!dialog.CheckFileExists)
                return false;
            return ResultIsOk(result);
        }

        public bool SaveFileDialog(out string file, string filetype, IWin32Window owner)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.AddExtension = true;
            dialog.DefaultExt = filetype;
            DialogResult result = ShowDialog(dialog, owner);
            file = dialog.FileName;
            return ResultIsOk(result);
        }
    }
}